<script setup>
import {computed, ref, watch} from "vue";
import {useQuasar} from "quasar";
import {api} from "boot/axios";
import {useAPIStore} from "stores/api";
import {status} from 'src/utils/deviceWs'

const $q = useQuasar();
const powerMethod = ref(true); // 供电方式,true为主电池供电,false为备用电池供电


const criticalValue = ref(status.value.battSpareD || 0); // 临界值

const isCharge = ref(false)

watch(() => status.value.gpioO, (newValue) => {
  if (!newValue) {
    return;
  }
  const top3 = newValue.join('').substring(0, 3) // 前3位
  if (top3 === '010') {
    // 备用电池放电
    powerMethod.value = false
  } else if (newValue.join('').substring(0, 2) === '00') {
    //主电池放电
    powerMethod.value = true
  }
  if (top3 === '001') {
    // 备用电池充电
    isCharge.value = true
  }
}, {
  immediate: true
})

watch(() => status.value.battSpareD, (newValue) => {
  criticalValue.value = newValue
})

watch(criticalValue, () => {
  if (criticalValue.value !== status.value.battSpareD) {
    setTimeout(() => {
      criticalValue.value = status.value.battSpareD || 0
    }, 1000)
  }
})

/**
 * 修改临界值
 */
function changeCriticalValue(value) {
  console.log("当前临界值", value);
  $q.dialog({
    title: "修改临界值",
    message: `是否要将当前临界值${status.value.battSpareD}%修改为${criticalValue.value}%`,
    cancel: true,
    persistent: true,
  })
    .onOk(() => {
      showPasswordDialog()
        .then(() => {
          return callService('SET_CAPACITY,13,' + (value * 10))
        })
      // .then(res => {
      //   if (res.data?.values?.result === 'SUCCESS') {
      //     criticalValue.value = value;
      //     $q.notify({message: `临界值修改成功${res}`, type: "positive"});
      //   } else {
      //     throw new Error(`临界值修改失败`)
      //   }
      // })
      // .catch((err) => {
      //   criticalValue.value = status.value.battSpareD;
      //   if (err && err.message) {
      //     $q.notify({message: `临界值修改失败：${err.message}`, type: "negative"});
      //   }
      // });
    })
    .onCancel(() => {
      criticalValue.value = status.value.battSpareD;
    });
}

/**
 * 调用换电方案相关service
 */
function callService(params) {
  return new Promise((resolve, reject) => {
    api.post(useAPIStore().amrUrl + "ros/call", {data: params}, {
      params: {service: "/send_message_todevice"},
    }).then(res => {
      if (res.data?.values.result === "SUCCESS") {
        resolve(res)
        $q.notify({message: `指令下发成功`, type: "positive"});
      } else {
        $q.notify({message: `指令下发失败`, type: "negative"});
      }
    }).catch(err => {
      reject(err)
      $q.notify({message: `指令下发失败`, type: "negative"});
    })
  })
}

/**
 * 弹出密码输入框
 */
function showPasswordDialog() {
  return new Promise((resolve, reject) => {
    $q.dialog({
      title: "提示",
      message: "该操作需要输入密码，请先输入密码",
      prompt: {
        model: "",
        type: "text", // optional
      },
      cancel: true,
      persistent: true,
    })
      .onOk((value) => {
        if (value === "sage") {
          resolve();
        } else {
          reject(new Error("密码错误，请重新输入"));
          $q.notify({message: `密码错误，请重新输入`, type: "negative"});
        }
      })
      .onCancel(() => {
        reject();
      });
  });
}

/**
 * 修改供电方式
 * @param {*} type 主电池还是备用电池
 */
function modifyPowerMethod(type, value) {
  console.log("🚀 ~ :", "type", type, value);
  showPasswordDialog()
    .then(() => {
      switch (type) {
        case "main":
          return callService('SET_REPLACE,OFF')
        case "spare":
          return callService('SET_REPLACE,ON')
      }
    }).then(res => {
    // 只需要下发指令，具体值还是根据gpioO来确定
    // switch (type) {
    //   case "main":
    //     powerMethod.value = true;
    //   case "spare":
    //     powerMethod.value = false;
    // }
    // $q.notify({message: `换电方案切换成功${res}`, type: "positive"});
  })
  // .catch((err) => {
  //   if (err && err.message) {
  //     $q.notify({message: `换电方案切换失败失败：${err.message}`, type: "negative"});
  //   }
  // });
}

/**
 * 使用主电池给备用电池充电
 */
function backupBatteryCharging() {
  $q.dialog({
    title: "提示",
    message: "确认使用主电池给备用电池充电吗？",
    cancel: true,
    persistent: true,
  })
    .onOk(() => {
      callService('SET_CHARGE')
      // .then(res => {
      //   if (res.data?.values?.result === "SUCCESS") {
      //     $q.notify({message: `指令下发成功`, type: "positive"});
      //   } else {
      //     throw new Error("指令下发失败")
      //   }
      // })
    })

}
</script>

<template>
  <div class="battery-container q-pa-md">
    <q-card class="full-height q-pa-md">
      <q-item tag="label" v-ripple @click.prevent="()=>{}">
        <q-item-section class="items-center">
          <q-item-label>主电池电量</q-item-label>
          <q-knob
            readonly
            :model-value="status.batteryNumber || 0"
            show-value
            size="90px"
            :thickness="0.22"
            color="primary"
            track-color="grey-4"
            class="text-orange q-ma-md"
          />
        </q-item-section>

        <q-item-section class="items-center">
          <q-item-label>备用电池电量</q-item-label>
          <q-knob
            readonly
            :model-value="status.battSpareN || 0"
            show-value
            size="60px"
            :thickness="0.22"
            color="primary"
            track-color="grey-4"
            class="text-orange q-ma-md"
          />
        </q-item-section>
        <q-item-section avatar>
          <q-btn color="primary" @click="backupBatteryCharging" :disable="isCharge">
            {{ isCharge ? '备用电池充电中' : '使用主电池给备用电池充电' }}
          </q-btn>
        </q-item-section>
      </q-item>

      <q-separator/>

      <q-item tag="label" v-ripple>
        <q-item-section>
          <q-item-label>主电池供电</q-item-label>
          <q-item-label caption>使用主电池供电</q-item-label>
        </q-item-section>
        <q-item-section avatar>
          <q-toggle
            color="green"
            :model-value="powerMethod"
            val="friend"
            @update:model-value="(val, evt) => modifyPowerMethod('main', val)"
          />
        </q-item-section>
      </q-item>

      <q-separator/>

      <q-item tag="label" v-ripple>
        <q-item-section>
          <q-item-label>备用电池供电</q-item-label>
          <q-item-label caption>使用备用电池供电</q-item-label>
        </q-item-section>
        <q-item-section avatar>
          <q-toggle
            color="red"
            :model-value="!powerMethod"
            val="picture"
            @update:model-value="(val, evt) => modifyPowerMethod('spare', val)"
          />
        </q-item-section>
      </q-item>

      <q-separator/>

      <q-item tag="label" v-ripple>
        <q-item-section>
          <q-item-label>当前临界值：{{ status.battSpareD || 0 }}%</q-item-label>
          <q-item-label caption
          >当前主电池临界值，拖动右侧线条上的圆点可修改临界值
          </q-item-label
          >
        </q-item-section>
        <q-item-section avatar>
          <q-badge color="secondary">
            临界值: {{ criticalValue }}% (临界值范围在10%~50%之间)
          </q-badge>

          <q-slider
            v-model="criticalValue"
            :min="0"
            :max="100"
            :inner-min="10"
            :inner-max="50"
            @change="changeCriticalValue"
          />
        </q-item-section>
      </q-item>
    </q-card>
  </div>
</template>

<style scoped>
.battery-container {
  width: 50%;
  margin: auto;
}
</style>
